package com.dldata.display.control.System;

import com.dldata.display.entity.SysDtwyZbbEntity;
import com.dldata.display.entity.SysKsEntity;
import com.dldata.display.entity.SysUserInfoEntity;
import com.dldata.display.service.System.SysDtwyZbbService;
import com.dldata.display.service.System.SysKeShiService;
import com.dldata.display.service.System.SysUserInfoService;
import com.dldata.display.utils.StringUtil;
import net.sf.json.JSONArray;
import org.apache.poi.hssf.usermodel.*;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 吴岳峰 on 2017/07/11.
 */
@Controller
@RequestMapping("/SysDtwyZbb")
public class SysDtwyZbbController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysKeShiService sysKeShiService;

    @Autowired
    private SysDtwyZbbService sysDtwyZbbService;

    @Autowired
    private SysUserInfoService sysUserInfoService;

    @RequestMapping("/save")
    public void save(HttpServletRequest request, HttpServletResponse response,
                     @RequestParam Map<String, Object> param)throws Exception {
        String result = "";
        Map<String, Object> entityMap = new HashMap<>();
        entityMap.putAll(param);
        SysDtwyZbbEntity sysDtwyZbbEntity = StringUtil.mapToObject(SysDtwyZbbEntity.class, entityMap);
        if(sysDtwyZbbEntity.getId()==null||sysDtwyZbbEntity.getId().equals("")){
            sysDtwyZbbEntity.setId(UUID.randomUUID().toString());
        }
        String rq =entityMap.get("rq").toString();
                String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar = Calendar.getInstance();
        if(rq != null){
            calendar.setTime(Timestamp.valueOf(rq+" 00:00:00"));
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
        }
        String week =  weekOfDays[w];
        sysDtwyZbbEntity.setWeek(week);
        try {
            sysDtwyZbbService.save(sysDtwyZbbEntity);
            result = "{\"success\":true,\"msg\":\"表单保存成功！\"}";
        } catch (Exception e) {
            result = "{\"success\":false,\"msg\":\"表单保存失败！\"}";
        }
        StringUtil.writeToWeb(result, "html", response);
    }


    @RequestMapping("/getZbKeshi")
    @ResponseBody
    public List<SysKsEntity> getZbkeshi(String search,String rq,
                                        @CookieValue(value = "userid",defaultValue = "")String userid,
                                        @CookieValue(value = "syscode",defaultValue = "")String syscode){
        List<SysKsEntity> sysKsList = sysKeShiService.findUserKs(userid,syscode);
        SysUserInfoEntity sysUserInfoEntity = sysUserInfoService.findByIdAndSysCode(userid,syscode);
        boolean isc = false;
        for (SysKsEntity sysKsEntity : sysKsList) {
            if(sysKsEntity.getPym().toLowerCase().indexOf("yw")>-1||sysUserInfoEntity.getLoginName().toLowerCase().equals("admin")){
                isc = true;
                break;
            }
        }
        if(isc){
            sysKsList =  sysKeShiService.findByCondition("%"+search+"%");
        }

        List<SysKsEntity> sysKsEntities = sysKsList.stream()
                .filter(k -> k.getPym().toLowerCase().indexOf(search.toLowerCase())>-1||k.getCode().indexOf(search)>-1||k.getName().indexOf(search)>-1)
                .collect(Collectors.toList());


        List<SysKsEntity> ksList = new ArrayList<SysKsEntity>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(Timestamp.valueOf(rq+"-01 00:00:00"));
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String day = format.format(calendar.getTime());
        Timestamp s = Timestamp.valueOf(rq.substring(0,7)+"-01 00:00:00");
        Timestamp e = Timestamp.valueOf(day+" 23:59:59");
        List<SysDtwyZbbEntity> sysDtwyZbbEntities = sysDtwyZbbService.findByKsMonth(s,e,"");
        sysKsEntities.forEach(k ->{
            sysDtwyZbbEntities.stream().filter(z -> z.getKsId().equals(k.getId())).limit(1).forEach(z -> {
                ksList.add(k);
            });
        });

        ksList.forEach(ks -> {
            List<SysKsEntity> ss = sysKsEntities.stream().filter(k -> ks.getId().equals(k.getId())).collect(Collectors.toList());
            sysKsEntities.removeAll(ss);
        });
        ksList.addAll(sysKsEntities);
        return ksList;
    }


    @RequestMapping("/getZbList")
    @ResponseBody
    public String getZbList(String ks,String rq){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(Timestamp.valueOf(rq+"-01 00:00:00"));
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String day = format.format(calendar.getTime());
        Timestamp s = Timestamp.valueOf(rq.substring(0,7)+"-01 00:00:00");
        Timestamp e = Timestamp.valueOf(day+" 23:59:59");
        List<SysDtwyZbbEntity> sysDtwyZbbEntities = sysDtwyZbbService.findByKsMonth(s,e,ks);
        List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
        sysDtwyZbbEntities.forEach(z -> {
            Map<String ,String> map = new HashMap<String ,String>();
            map.put("id",z.getId());
            map.put("rq",z.getRq().toString().substring(0,10));
            map.put("week",z.getWeek());
            map.put("userName",z.getUserName());
            map.put("type",z.getType());
            map.put("bz",z.getBz());
            mapList.add(map);
        });

        return mapList.size()>0? JSONArray.fromObject(mapList).toString():"[]";
    }

    @RequestMapping(value = "/delete")
    public void delete(String id,HttpServletRequest request, HttpServletResponse response)throws Exception{
        String result;
        try {
            sysDtwyZbbService.delete(id);
            result = "{\"success\":true,\"msg\":\"删除成功！\"}";
        }
        catch (Exception ex){
            result = "{\"success\":false,\"msg\":\"删除失败！\"}";
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage());
        }
        StringUtil.writeToWeb(result, "html", response);
    }

    @RequestMapping("/doExcel")
    public void doExcel(String ks,String rq,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        String result = "";
        try {
            // 1.创建一个workbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");

            String fileName = "数据表.xls";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 2.在workbook中添加一个sheet，对应Excel中的一个sheet
            HSSFSheet sheet = wb.createSheet("数据表");
            HSSFFont font = wb.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 16);
            // 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);
            // 4.创建单元格，设置值表头，设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            // 居中格式
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 设置表头
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("序号");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("日期");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("星期");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("值班类型");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("备注");
            cell.setCellStyle(style);



            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(Timestamp.valueOf(rq+"-01 00:00:00"));
            calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            String day = format.format(calendar.getTime());
            Timestamp s = Timestamp.valueOf(rq.substring(0,7)+"-01 00:00:00");
            Timestamp e = Timestamp.valueOf(day+" 23:59:59");
            List<SysDtwyZbbEntity> sysDtwyZbbEntities = sysDtwyZbbService.findByKsMonth(s,e,ks);
            List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
            sysDtwyZbbEntities.forEach(z -> {
                Map<String ,String> map = new HashMap<String ,String>();
                map.put("id",z.getId());
                map.put("rq",z.getRq().toString().substring(0,10));
                map.put("week",z.getWeek());
                map.put("userName",z.getUserName());
                map.put("type",z.getType());
                map.put("bz",z.getBz());
                mapList.add(map);
            });

            for (int i = 0; i < mapList.size(); i++) {
                row = sheet.createRow((int) i + 1);
                Map dmap = (Map) mapList.get(i);
                //创建行
                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue((String) dmap.get("rq"));
                row.createCell(2).setCellValue((String) dmap.get("week"));
                row.createCell(3).setCellValue((String) dmap.get("userName"));
                row.createCell(4).setCellValue((String) dmap.get("type"));
                row.createCell(5).setCellValue((String) dmap.get("bz"));
            }
            try {
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } catch (ServiceException ex) {
                result = "{\"success\":false,\"msg\":\"文件导出失败！\"}";
            } catch (Exception e1) {
                result = "{\"success\":false,\"msg\":\"文件导出失败！\"}";
            }
            result = "{\"success\":true,\"msg\":\"文件导出成功！\"}";
        } catch (Exception ex) {
            result = "{\"success\":false,\"msg\":\"文件导出失败！\"}";
        }
        StringUtil.writeToWeb(result, "html", response);
    }

}
